package utils;



import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import androidx.lifecycle.AndroidViewModel;

/**
 * Created by jingbin on 2018/12/26.
 */

public class ClassUtil {

    /**
     * 获取泛型ViewModel的class对象
     */
    public static <T> Class<T> getViewModel(Object obj) {



       return getTClass(obj.getClass());
    }

    private  static  <T> Class<T>  getTClass(Class c){
        Class<T> tClass = getGenericClass(c, AndroidViewModel.class);

        if (tClass == null  ) {

            if(c.getSuperclass().equals(Object.class))
            {
                return  null;
            }
            return getTClass(c.getSuperclass());

        }else if(tClass == AndroidViewModel.class  ) {

            return null;
        }else {
            return  tClass;
        }
    }

    private static <T> Class<T> getGenericClass(Class<?> klass, Class<?> filterClass) {
        Type type = klass.getGenericSuperclass();
        if (type == null || !(type instanceof ParameterizedType)) return null;
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type[] types = parameterizedType.getActualTypeArguments();
        for (Type t : types) {
            Class<T> tClass = (Class<T>) t;
            if (filterClass.isAssignableFrom(tClass)) {
                return tClass;
            }
        }
        return null;
    }
}
